package com.itheima.web;

import com.itheima.pojo.User;
import com.itheima.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    private UserService service = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 封装对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);


        //获取用户输入的验证码
        String checkCode = request.getParameter("checkCode");
        //获取服务器生成的验证码
        HttpSession session = request.getSession();
        String checkCodeGen = (String) session.getAttribute("checkCodeGen");

        //比对数据
        if (!checkCodeGen.equalsIgnoreCase(checkCode)) {   //注意把机器生成的验证码放在前面 因为机器一定不为空，而人工输出的可能为空
            request.setAttribute("register_msg", "验证码错误");
            request.getRequestDispatcher("/register.jsp").forward(request,response);//每次都是因为没有forward导致白屏

            //不允许注册
            return;
        }


        //2. 调用service注册
        boolean flag = service.register(user);

        //3. 判断是否注册成功
        if (flag) {
            // 注册成功，跳转到登录页面

            request.setAttribute("register_msg", "注册成功，请登录！");//注册成功注释
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        } else {
            //注册失败，跳转到注册页面

            request.setAttribute("register_msg", "用户名已存在");//注册失败注释
            request.getRequestDispatcher("/register.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
